<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Requests\Api\CommentRequest;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use App\Models\Article;
use App\Models\Tags;
use App\Models\ArticleTag;
use App\Models\User;
use App\Models\Chat;
use App\Models\Comment;
use DB;
use session;

class ArticleController extends Controller
{
	// 初始化操作
	public function __construct()
	{
		// 获取最热文章
		if(Cache::has('hot_article')){
            $hot_article = Cache::get('hot_article');
        } else {
            $hot_article = Article::where('is_show',1)->select('aid','title','created_at','updated_at','cid','author','keywords','click','comment_num','description')->with('category','articlepic')->orderBy('click','desc')->limit(8)->get();
            Cache::put('hot_article',$hot_article,3600*24);
        }

        // 获取标签
        if(Cache::has('article_tag')){
            $article_tag = Cache::get('article_tag');
        } else {
            $article_tag = Tags::select('tid','tname')->orderBy('tid','desc')->get();
            Cache::put('article_tag',$article_tag,3600*24*7);
        }

        view()->share('hot_article',$hot_article);
        view()->share('article_tag',$article_tag);
	}

    // 文章搜索
    public function articleSearch(Request $request)
    {
    	# 查询关键词
    	$keyword = $request->input('keyword','','htmlspecialchars');
    	if(!empty($keyword)) {
    		# 查询符合条件的文章
    		$article_list = Article::where('title','like','%'.$keyword.'%')->select('aid','title','created_at','updated_at','cid','author','keywords','click','comment_num','description')->with('category','articlepic')->orderBy('sort','desc')->get();
    	}

    	# 查询标签ID
    	$tid = $request->input('tid');
    	if(!empty($tid)){
    		if(!preg_match('/^[1-9]\d*$/', $tid)) return redirect('/prompt')->with(['message'=>'请选择正确的标签','url' =>'/', 'jumpTime'=>3,'status'=>'error']);
    		# 根据标签ID查询文章ID列表
    		$article_tag = ArticleTag::where('tid',$tid)->select('aid')->get();
    		foreach ($article_tag as $k => $v) {
    			$article_list[$k] = Article::where('aid',$v['aid'])->select('aid','title','created_at','updated_at','cid','author','keywords','click','comment_num','description')->with('category','articlepic')->orderBy('sort','desc')->first();
    		}
    	}

    	if(!$tid && !$keyword){
    		return redirect('/prompt')->with(['message'=>'请输入搜索关键词','url' =>'/', 'jumpTime'=>3,'status'=>'error']);
    	}

    	return view('home.Article.articleSearch',['article_list'=>$article_list,'keyword'=>$keyword]);
    }

    // 文章列表
    public function articleList(Request $request,$cid)
    {
    	# 获取文章列表
    	$page = $request->input('page','1');

    	if(Cache::has($cid.'_article_type_'.$page)){
            $article_type = Cache::get($cid.'_article_type_'.$page);
        } else {
            $article_type = Article::where(['cid'=>$cid,'is_show'=>1])->select('aid','title','created_at','updated_at','cid','author','keywords','click','comment_num','description')->with('category','articlepic')->orderBy('sort','desc')->paginate(12);
            Cache::put($cid.'_article_type_'.$page,$article_type,3600*24);
        }

        return view('home.Article.articleList',['article_type'=>$article_type]);
    }

    // 文章详情
    public function articleDetail($aid)
    {
        # 增加浏览量
        Article::where(['aid'=>$aid])->increment('click');
    	# 获取网站统计数据
    	$article_count = Article::count();
    	$time = timediff(1493568000,time());

    	# 查询详情
    	$detail = Article::where(['is_show'=>1,'aid'=>$aid])->select('aid','cid','title','created_at','author','click','comment_num','content','description')->with('category')->first();
    	# 相关文章查询
    	$relation_article = Article::where(['is_show'=>1,'cid'=>$detail->cid])->select('aid','title')->limit(5)->get();

    	# 获取文章评论
    	$comment_list = Comment::where(['status'=>1,'aid'=>$detail->aid])->select('contents','uid','created_at','email','cmtid')->get();
    	foreach ($comment_list as $k => $v) {
    		# 查询用户信息
    		$user = User::where('uid',$v['uid'])->select('head_img','username')->first();
    		$comment_list[$k]['created_at'] = date('Y-m-d H:i',$v['created_at']);
    		$comment_list[$k]['head_img'] = $user['head_img'];
    		$comment_list[$k]['username'] = $user['username'];
    	}
    	$comment = $comment_list->toArray();
    	return view('home.Article.articleDetail',['detail'=>$detail,'relation_article'=>$relation_article,'comment'=>json_encode($comment),'article_count'=>$article_count,'time'=>$time]);
    }

    // 源码分享
    public function codeShare()
    {
    	return view('home.Article.codeShare');
    }

    // 随心笔记
    public function chat()
    {
    	# 获取笔记
    	$chat_list = Chat::where('is_show',1)->select('chid','create_time','content')->orderBy('chid','desc')->get();
    	foreach ($chat_list as $key => $value) {
    		$chat_list[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
    	}
    	return view('home.Chat.chat',['chat_list'=>$chat_list]);
    }

    // 评论添加
    public function addComment(CommentRequest $request,Comment $comment)
    {
        $comment->uid = session('users.uid');
        $comment->aid = $request->aid;
        $comment->contents = htmlspecialchars($request->contents);
        $comment->created_at = time();
        $comment->email = $request->email;
        $res = $comment->save();
        if($res){
            return ['status'=>1,'msg'=>'评论成功'];
        } else {
            return ['status'=>0,'msg'=>'评论失败'];
        }
    }



}
